package com.apes.fn.mdm.supplierConfiguration;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;

import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SupplierBusinessScope.CONST_TABLE_NAME,
        indexes={@Index(columnList = "supplier_id", unique = true)})
public class SupplierBusinessScope extends Model {
    public static final String CONST_TABLE_NAME = "mas_supplier_business_scope";

    @Id
    @Column(name = "id", length = 4)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "急件供应商配置",padding = 4)
    @Comment("编码")
    private String id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplierId;

    @Column(name = "supplier_tax", nullable = false, columnDefinition = "number(3, 0) default 0")
    @Comment("供应商税率")
    private int supplierTax;

    @Column(name = "install_supplier", nullable = false, columnDefinition = "number(2, 0) default 1")
    @Comment("装机供应商")
    private boolean installSupplier;

    @Column(name = "push_single_calendar", length = 400)
    @Comment("推单日历")
    private String pushSingleCalendar;

    @Column(name = "defualt_supplier_operator")
    @Comment("默认供应商操作员")
    private String defualtSupplierOperator;

    @Column(name = "defualt_supplier_operator_name")
    @Comment("默认供应商操作员名称")
    private String defualtSupplierOperatorName;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "operator_status", referencedColumnName = "id")
    @Comment("操作员状态")
    private Enumeration operatorStatus;

    @Transient
    @Comment("老框架供应商")
    private String gysid;

    @Transient
    @Comment("供应商简称")
    private String abbreviation;

    public String getGysid() {
        return this.supplierId.getParty().getOrigin();
    }

    public String getAbbreviation() {
        return this.supplierId.getParty().getAbbreviation();
    }

    @OneToMany(mappedBy = "supplierBusinessScopeId", cascade = CascadeType.ALL, orphanRemoval = true)
    List<SupplierBrand> supplierBrands = new ArrayList<>();

    public List<SupplierBrand> getSupplierBrands() {
        String distinctBrand = "";
        for (SupplierBrand supplierBrand : supplierBrands) {
            String carlabelId = supplierBrand.getCarLabelId().getId();
            if (StringUtils.hasText(distinctBrand) && distinctBrand.indexOf(carlabelId) != -1) throw new RuntimeException("厂牌重复, 厂牌: " + carlabelId);
            distinctBrand += carlabelId + ";";
            supplierBrand.setSupplierBusinessScopeId(this);
        }
        return supplierBrands;
    }

    @OneToMany(mappedBy = "supplierBusinessScopeId", cascade = CascadeType.ALL, orphanRemoval = true)
    List<SupplierClassify> supplierClassifies = new ArrayList<>();

    public List<SupplierClassify> getSupplierClassifies() {
        String distinctClassify = "";
        for (SupplierClassify supplierClassify : supplierClassifies) {
            String classifyId = supplierClassify.getClassifyId().getId();
            if (StringUtils.hasText(distinctClassify) && distinctClassify.indexOf(classifyId + ";") != -1) {
                throw new RuntimeException("品类重复, 品类: " + classifyId);
            }
            distinctClassify += classifyId + ";";
            supplierClassify.setSupplierBusinessScopeId(this);
        }
        return supplierClassifies;
    }

    public int getSupplierTax() {
        return JSONObject.parseObject(SpringManager.getBean(DomainService.class).
                invoke("condition.execConditionStrategy",
                        MapUtil.mapper("SUPPLIER_ID", this.supplierId.getId(), "SYS_RQ", new Date(),"conditionStrategyId", "CG11")
                ).toString()).getIntValue("P101");
    }
}
